<template>
  <div class="movie-view">
    <div v-if="movieStore.loading" class="loading">加载中...</div>
    
    <div v-else-if="movieStore.error" class="error">
      {{ movieStore.error }}
      <button @click="goBack" class="back-btn">返回</button>
    </div>
    
    <div v-else-if="movieStore.currentMovie" class="movie-detail">
      <!-- 电影基本信息 -->
      <div class="movie-header">
        <button @click="goBack" class="back-btn">← 返回</button>
        <div class="header-content">
          <img :src="movieStore.currentMovie.filmImg" :alt="movieStore.currentMovie.name" class="movie-poster" />
          <div class="movie-meta">
            <h1>{{ movieStore.currentMovie.name }}</h1>
            <h2>{{ movieStore.currentMovie.nameEnglish }}</h2>
            <div class="meta-grid">
              <div class="meta-item">
                <label>类型:</label>
                <span>{{ movieStore.currentMovie.storyType }}</span>
              </div>
              <div class="meta-item">
                <label>时长:</label>
                <span>{{ movieStore.currentMovie.timeLength }}分钟</span>
              </div>
              <div class="meta-item">
                <label>影院:</label>
                <span>{{ movieStore.currentMovie.cinema }} {{ movieStore.currentMovie.room }}</span>
              </div>
              <div class="meta-item">
                <label>时间:</label>
                <span>{{ formatDateTime(movieStore.currentMovie.showTime) }}</span>
              </div>
              <div class="meta-item">
                <label>价格:</label>
                <span class="price">¥{{ movieStore.currentMovie.unitPrice }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 座位选择区域 -->
      <div class="seat-selection">
        <h3>选择座位（最多可选5个）</h3>
        
        <!-- 购票表单 -->
        <div class="booking-form">
          <input 
            v-model="buyerName" 
            type="text" 
            placeholder="请输入您的姓名" 
            class="name-input"
          />
        </div>

        <!-- 座位图 -->
        <div class="seat-map">
          <div 
            v-for="(seat, index) in movieStore.seats" 
            :key="index"
            :class="[ 'seat', seat === 1 ? 'occupied' : 'available', selectedSeats.includes(index + 1) ? 'selected' : '' ]"
            @click="selectSeat(index + 1)"
          >
            {{ index + 1 }}
          </div>
        </div>

        <!-- 选座信息 -->
        <div class="selection-info">
          <p>已选座位：{{ selectedSeats.join(', ') || '无' }}</p>
          <p>已选数量：{{ selectedSeats.length }} / 5</p>
          <p class="total-price">总价：¥{{ totalPrice }}</p>
          <button 
            v-if="selectedSeats.length > 0" 
            @click="clearSelection" 
            class="clear-btn"
          >
            清空选择
          </button>
        </div>

        <!-- 座位图例 -->
        <div class="seat-legend">
          <div class="legend-item">
            <div class="seat available"></div>
            <span>可选</span>
          </div>
          <div class="legend-item">
            <div class="seat occupied"></div>
            <span>已售</span>
          </div>
          <div class="legend-item">
            <div class="seat selected"></div>
            <span>已选</span>
          </div>
        </div>

        <!-- 购票按钮 -->
        <button 
          @click="purchaseTicket" 
          :disabled="!canPurchase"
          class="purchase-btn"
        >
          {{ purchaseBtnText }}
        </button>

        <!-- 购票结果 -->
        <div v-if="purchaseResult" class="purchase-result">
          <div v-if="purchaseResult.success" class="success">
            ✅ 购票成功！座位号: {{ purchaseResult.seatNumbers.join(', ') }}
          </div>
          <div v-else class="error">
            ❌ {{ purchaseResult.message }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { useMovieStore } from '../stores/movie'
import { onMounted, ref, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'

export default {
  name: 'MovieView',
  props: ['id'],
  setup(props) {
    const movieStore = useMovieStore()
    const router = useRouter()
    const route = useRoute()
    
    const selectedSeats = ref([])
    const buyerName = ref('')
    const purchaseResult = ref(null)

    const movieId = computed(() => props.id || route.params.id)

    onMounted(async () => {
      if (movieId.value) {
        await movieStore.fetchMovie(movieId.value)
        await movieStore.fetchSeats(movieId.value)
      }
    })

    watch(() => route.params.id, async (newId) => {
      if (newId) {
        await movieStore.fetchMovie(newId)
        await movieStore.fetchSeats(newId)
        resetSelection()
      }
    })

    const resetSelection = () => {
      selectedSeats.value = []
      buyerName.value = ''
      purchaseResult.value = null
    }

    const selectSeat = (seatNumber) => {
      if (movieStore.seats[seatNumber - 1] === 0) {
        const index = selectedSeats.value.indexOf(seatNumber)
        if (index > -1) {
          selectedSeats.value.splice(index, 1)
        } else {
          if (selectedSeats.value.length < 5) {
            selectedSeats.value.push(seatNumber)
          } else {
            // 前端限制提示
            purchaseResult.value = {
              success: false,
              message: '一次最多只能选择5个座位'
            }
          }
        }
        purchaseResult.value = null
      }
    }

    const clearSelection = () => {
      selectedSeats.value = []
      purchaseResult.value = null
    }

    const totalPrice = computed(() => {
      if (!movieStore.currentMovie || selectedSeats.value.length === 0) return 0
      return (movieStore.currentMovie.unitPrice * selectedSeats.value.length).toFixed(2)
    })

    const canPurchase = computed(() => {
      return selectedSeats.value.length > 0 && buyerName.value.trim()
    })

    const purchaseBtnText = computed(() => {
      if (selectedSeats.value.length === 0) return '请选择座位'
      if (!buyerName.value.trim()) return '请输入姓名'
      return `购买 ${selectedSeats.value.length} 个座位 - 总计 ¥${totalPrice.value}`
    })

    const purchaseTicket = async () => {
      if (!canPurchase.value) return

      try {
        if (selectedSeats.value.length === 1) {
          await movieStore.purchaseTicket(
            movieId.value,
            selectedSeats.value[0],
            buyerName.value.trim()
          )
        } else {
          await movieStore.purchaseTicketsBatch(
            movieId.value,
            selectedSeats.value,
            buyerName.value.trim()
          )
        }
        
        purchaseResult.value = {
          success: true,
          seatNumbers: [...selectedSeats.value]
        }
        
        selectedSeats.value = []
        buyerName.value = ''
        
      } catch (error) {
        purchaseResult.value = {
          success: false,
          message: error.message
        }
      }
    }

    const goBack = () => {
      router.push('/')
    }

    const formatDateTime = (dateTimeStr) => {
      return new Date(dateTimeStr).toLocaleString('zh-CN')
    }

    return {
      movieStore,
      selectedSeats,
      buyerName,
      purchaseResult,
      selectSeat,
      clearSelection,
      totalPrice,
      canPurchase,
      purchaseBtnText,
      purchaseTicket,
      goBack,
      formatDateTime
    }
  }
}
</script>

<style scoped>
.movie-view {
  max-width: 1000px;
  margin: 0 auto;
  color: #e0e0e0;
}

.back-btn {
  background: #444;
  color: #fff;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 5px;
  cursor: pointer;
  margin-bottom: 1rem;
  transition: background 0.3s;
}

.back-btn:hover {
  background: #666;
}

.movie-header {
  background: #1e1e1e;
  border-radius: 10px;
  padding: 2rem;
  margin-bottom: 2rem;
  box-shadow: 0 4px 15px rgba(0,0,0,0.6);
}

.header-content {
  display: flex;
  gap: 2rem;
  align-items: flex-start;
  justify-content: flex-start;
}

.movie-poster {
  width: 200px;
  height: 300px;
  object-fit: contain;
  border-radius: 5px;
  background: #000;
}

.movie-meta {
  margin-left: 2rem;
}

.movie-meta h1 {
  color: #fff;
  margin-bottom: 0.5rem;
}

.movie-meta h2 {
  color: #bbb;
  font-style: italic;
  margin-bottom: 1.5rem;
}

.meta-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
}

.meta-item {
  display: flex;
  justify-content: space-between;
  padding: 0.5rem 0;
  border-bottom: 1px solid #333;
}

.meta-item label {
  font-weight: bold;
  color: #aaa;
}

.meta-item .price {
  color: #ff4d4d;
  font-weight: bold;
}

.seat-selection {
  background: #1e1e1e;
  border-radius: 10px;
  padding: 2rem;
  box-shadow: 0 4px 15px rgba(0,0,0,0.6);
}

.seat-selection h3 {
  color: #fff;
  margin-bottom: 1rem;
}

.booking-form {
  margin-bottom: 2rem;
}

.name-input {
  width: 300px;
  padding: 0.75rem;
  border: 2px solid #444;
  border-radius: 5px;
  font-size: 1rem;
  background: #121212;
  color: #fff;
}

.name-input:focus {
  outline: none;
  border-color: #ff4d4d;
}

.seat-map {
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  gap: 0.5rem;
  margin-bottom: 2rem;
  padding: 1rem;
  background: #121212;
  border-radius: 10px;
}

.seat {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #2ecc71;
  color: white;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 0.8rem;
}

.seat.available:hover {
  background: #27ae60;
  transform: scale(1.1);
}

.seat.occupied {
  background: #c0392b;
  cursor: not-allowed;
}

.seat.selected {
  background: #f1c40f;
  color: #333;
  transform: scale(1.1);
}

/* 新增样式 */
.selection-info {
  margin: 1rem 0;
  padding: 1rem;
  background: #2a2a2a;
  border-radius: 5px;
  color: #e0e0e0;
}

.total-price {
  color: #ff4d4d;
  font-weight: bold;
  font-size: 1.1rem;
}

.clear-btn {
  background: #666;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 5px;
  cursor: pointer;
  margin-top: 0.5rem;
  transition: background 0.3s;
}

.clear-btn:hover {
  background: #888;
}

.seat-legend {
  display: flex;
  justify-content: center;
  gap: 2rem;
  margin-bottom: 2rem;
  color: #bbb;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.legend-item .seat {
  cursor: default;
  transform: none;
}

.purchase-btn {
  width: 100%;
  padding: 1rem;
  background: #ff4d4d;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 1.2rem;
  cursor: pointer;
  transition: background 0.3s;
}

.purchase-btn:hover:not(:disabled) {
  background: #e63939;
}

.purchase-btn:disabled {
  background: #555;
  cursor: not-allowed;
}

.purchase-result {
  margin-top: 1rem;
  padding: 1rem;
  border-radius: 5px;
  text-align: center;
  font-weight: bold;
}

.purchase-result.success {
  background: rgba(40, 167, 69, 0.2);
  color: #4caf50;
}

.purchase-result.error {
  background: rgba(178, 34, 34, 0.2);
  color: #ff6b6b;
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    text-align: center;
  }
  
  .movie-poster {
    align-self: center;
  }
  
  .seat-map {
    grid-template-columns: repeat(auto-fill, 40px);
    justify-content: center;
  }

  .movie-meta {
    margin-left: 0;
    margin-top: 1rem;
  }
  
  .name-input {
    width: 100%;
  }
}
</style>